package com.ruoyi.web.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.ClientUtils;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.app.*;
import com.ruoyi.system.mapper.CommunityMapper;
import com.ruoyi.system.mapper.CommunityMemberMapper;
import com.ruoyi.system.mapper.UserMapper;
import com.ruoyi.system.mapper.app.CardMapper;
import com.ruoyi.system.mapper.app.PowerCurveMapper;
import com.ruoyi.system.mapper.app.RechargeOrderMapper;
import com.ruoyi.system.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Api(tags = "订单相关")
@RestController
@RequestMapping("/order")
public class OrderController extends BaseController {

    @Autowired
    OrderService orderService;

    @Autowired
    RechargeOrderMapper rechargeOrderMapper;

    @Autowired
    RedisCache redisCache;
    @Autowired
    PowerCurveMapper powerCurveMapper;
    @Autowired
    CommunityMemberMapper communityMemberMapper;
    @Autowired
    CardMapper cardMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    CommunityMapper communityMapper;


    @ApiOperation(value = "获取融合充值订单列表",notes = "system:charge:list")
    @PreAuthorize("@ss.hasPermi('system:charge:list')")
    @GetMapping("/charge-list")
    public AjaxResult chargeOrder(String orderNo,String userName,String phone,String operatorName,String communityName,String startTime ,String endTime ){
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setUserName(userName);
        order.setUserPhone(phone);
        order.setOperatorName(operatorName);
        order.setCommunityName(communityName);
        startPage();
        return AjaxResult.success(getDataTable(orderService.chargeOrderList(order,startTime,endTime)));
    }

    @ApiOperation(value = "获取各个订单详细",notes = "system:charge:info type 1钱包充值 2包月充值 3电卡充值")
    @PreAuthorize("@ss.hasPermi('system:charge:info')")
    @GetMapping("/charge-info")
    public AjaxResult orderInfo(@RequestParam Long id, @RequestParam Integer type){

        return orderService.orderInfo(id,type);
    }

    @ApiOperation(value = "获取充电订单",notes = "system:recharge:list")
    @PreAuthorize("@ss.hasPermi('system:recharge:list')")
    @GetMapping("/recharge-list")
    public AjaxResult rechargeList(String orderNo,String userName,String phone,String deviceNum,String operatorName,String communityName,String startTime ,String endTime){
        RechargeOrder rechargeOrder = new RechargeOrder();
        rechargeOrder.setOrderNum(orderNo);
        rechargeOrder.setUserName(userName);
        rechargeOrder.setUserPhone(phone);
        rechargeOrder.setDeviceNum(deviceNum);
        rechargeOrder.setOperatorName(operatorName);
        rechargeOrder.setCommunityName(communityName);
        startPage();
        return AjaxResult.success(getDataTable(orderService.rechargeList(rechargeOrder,startTime,endTime)));
    }

    @ApiOperation(value = "订单退款",notes = "system:charge:refund")
    @PreAuthorize("@ss.hasPermi('system:charge:refund')")
    @PostMapping("/refund")
    public AjaxResult orderRefund(@RequestParam Long orderId, @RequestParam BigDecimal refundMoney){
        orderService.orderRefund(orderId,refundMoney);
        return AjaxResult.success();
    }


    @ApiOperation("web手动结束充电订单")
    @PostMapping("/web-end-recharge")
    public AjaxResult endRecharge(@RequestParam String orderNo) throws InterruptedException {

        RechargeOrder rechargeOrder = rechargeOrderMapper.selectByOrderNo(orderNo);
        if (rechargeOrder.getState() != 1) {
            throw new ServiceException("当前订单未在充电中！");
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = ClientUtils.doGetMethod("http://localhost:8610/end/charge?orderNo=" + rechargeOrder.getOrderNum());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (StringUtils.isNull(jsonObject) || !"200".equals(jsonObject.getString("code"))) {
            throw new ServiceException("结束失败！请稍后再试。");
        }
        //当前线程睡眠5秒，等待设备响应/orderStop 更改订单状态 扣款
        Thread.sleep(5000);
        RechargeOrder rechargeOrder2 = rechargeOrderMapper.selectByOrderNo(orderNo);
        if(rechargeOrder2.getState()!=4 || rechargeOrder2.getOrderState() !=4 ){
            RechargeOrder rechargeOrder1 = new RechargeOrder();
            rechargeOrder1.setId(rechargeOrder.getId());
            rechargeOrder1.setEndCause("0");
            rechargeOrder1.setOrderState(4);
            rechargeOrder1.setState(4);
            rechargeOrder1.setRechargeEndTime(new Date());
            rechargeOrderMapper.updateByPrimaryKeySelective(rechargeOrder1);
            deductMoney(rechargeOrder);
        }

        return AjaxResult.success();
    }

    @ApiOperation("订单曲线")
    @GetMapping("/recharge-curve")
    public AjaxResult orderRate(String order_no, String startTime, String endTime, HttpServletRequest request) {
        List<PowerCurve> cacheList = redisCache.getCacheList(Constants.RECHARGE_ORDER + order_no);
        if(cacheList==null || cacheList.size()==0){
            startPage();
            return AjaxResult.success(getDataTable(powerCurveMapper.selectByOrderNo(order_no,startTime,endTime)));
        }
        if(request.getParameter("pageNum")!=null && request.getParameter("pageSize")!=null){
            List<PowerCurve> collect = cacheList.stream().skip((Integer.valueOf(request.getParameter("pageNum")) - 1) * Integer.valueOf(request.getParameter("pageSize"))).limit(Long.valueOf(request.getParameter("pageSize"))).
                    collect(Collectors.toList());

            if(startTime!=null && endTime!=null){
                List<PowerCurve> list1 = new ArrayList<>();
                for (PowerCurve powerCurve : collect) {
                    long starttime = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", startTime).getTime();
                    long endtime = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", endTime).getTime();
                    if(powerCurve.getCreateTime().getTime()>=starttime && powerCurve.getCreateTime().getTime()<=endtime ){
                        list1.add(powerCurve);
                    }
                }
                collect.clear();
                collect.addAll(list1);
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("rows",collect);
            jsonObject.put("total",cacheList.size());
            return AjaxResult.success(jsonObject);
        }
        return AjaxResult.success();

    }

    private void deductMoney(RechargeOrder rechargeOrder){
        User user = userMapper.selectByPrimaryKey(rechargeOrder.getUserId());
        //余额扣款
        if (rechargeOrder.getPayType() == 1) {
            //订单结束
            Community community = communityMapper.selectByPrimaryKey(rechargeOrder.getCommunityId());
            CommunityMember communityMember = communityMemberMapper.selectByUser(user.getId(), rechargeOrder.getCommunityId());
            //余额通用
            if (StringUtils.isNull(communityMember) || community.getIsBalanceUse() == 1) {
                //扣款
                BigDecimal countMoney = rechargeOrder.getAllMoney();
                log.info("订单金额：" + countMoney);

                List<CommunityMember> communityMembers = communityMemberMapper.getCommunityMembersByOperatorId(user.getId(), rechargeOrder.getOperatorId());
                for (CommunityMember communityMember1 : communityMembers) {

                    if (countMoney.doubleValue() <= communityMember1.getBalance().doubleValue()) {
                        communityMember1.setBalance(communityMember1.getBalance().subtract(countMoney));
                        countMoney = BigDecimal.valueOf(0);
                        log.info("金额小于余额");
                        log.info(communityMember1.getBalance() + "");
                        log.info(communityMember1.getDiscountBalance() + "");
                        log.info(countMoney + "");
                    } else if (countMoney.doubleValue() > communityMember1.getBalance().doubleValue()) {
                        countMoney = countMoney.subtract(communityMember1.getBalance());
                        communityMember1.setBalance(new BigDecimal("0"));
                        log.info("金额大于余额");
                        log.info(communityMember1.getBalance() + "");
                        log.info(communityMember1.getDiscountBalance() + "");
                        log.info(countMoney + "");
                    }
                    if (countMoney.doubleValue() <= communityMember1.getDiscountBalance().doubleValue()) {
                        communityMember1.setDiscountBalance(communityMember1.getDiscountBalance().subtract(countMoney));
                        countMoney = BigDecimal.valueOf(0);
                        log.info("金额小于活动余额");
                        log.info(communityMember1.getBalance() + "");
                        log.info(communityMember1.getDiscountBalance() + "");
                        log.info(countMoney + "");
                    } else if (countMoney.doubleValue() > communityMember1.getDiscountBalance().doubleValue()) {
                        countMoney = countMoney.subtract(communityMember1.getDiscountBalance());
                        communityMember1.setDiscountBalance(new BigDecimal("0"));
                        log.info("金额大于活动余额");
                        log.info(communityMember1.getBalance() + "");
                        log.info(communityMember1.getDiscountBalance() + "");
                        log.info(countMoney + "");
                    }
                    communityMemberMapper.updateByPrimaryKeySelective(communityMember1);
                    if (countMoney.doubleValue() == 0D) {
                        break;
                    }
                }
            }
            // 没开启余额通用
            if (StringUtils.isNotNull(communityMember) &&  community.getIsBalanceUse() == 0) {
                //余额
                if (rechargeOrder.getPayType() == 1) {
                    //扣款
                    BigDecimal orderMoney = rechargeOrder.getAllMoney();
                    log.info("订单金额" + orderMoney.toPlainString());

                    if (orderMoney.doubleValue() <= communityMember.getBalance().doubleValue()) {
                        communityMember.setBalance(communityMember.getBalance().subtract(orderMoney));
                        log.info("真实金额" + communityMember.getBalance().toPlainString());
                    } else if (orderMoney.doubleValue() <= communityMember.getDiscountBalance().doubleValue()) {
                        communityMember.setDiscountBalance(communityMember.getDiscountBalance().subtract(orderMoney));
                        log.info("活动金额" + communityMember.getDiscountBalance().toPlainString());
                    } else  {
                        communityMember.setBalance(communityMember.getBalance().subtract(orderMoney));
                        communityMember.setDiscountBalance(communityMember.getBalance().add(communityMember.getDiscountBalance()));
                        communityMember.setBalance(new BigDecimal("0"));
                    }
                    //余额为负数重置为0
                    if(communityMember.getDiscountBalance().doubleValue()<0){
                        communityMember.setDiscountBalance(new BigDecimal("0"));
                    }
                    if(communityMember.getBalance().doubleValue()<0){
                        communityMember.setBalance(new BigDecimal("0"));
                    }

                    communityMemberMapper.updateByPrimaryKeySelective(communityMember);
                }

            }
        }
        //电卡
        else if (rechargeOrder.getPayType() == 3) {
            Card card = cardMapper.selectByNum(rechargeOrder.getCardNo());
            //扣款
            BigDecimal orderMoney = rechargeOrder.getAllMoney();
            if (orderMoney.doubleValue() <= card.getDiscountsMoney().doubleValue()) {
                card.setDiscountsMoney(card.getDiscountsMoney().subtract(orderMoney));
            } else if (orderMoney.doubleValue() <= card.getMoney().doubleValue()) {
                card.setMoney(card.getMoney().subtract(orderMoney));
            } else  {
                card.setMoney(card.getMoney().subtract(orderMoney));
                card.setDiscountsMoney(card.getDiscountsMoney().add(card.getMoney()));
                card.setMoney(new BigDecimal("0"));
            }
            //余额为负数重置为0
            if(card.getDiscountsMoney().doubleValue()<0){
                card.setDiscountsMoney(new BigDecimal("0"));
            }
            if(card.getMoney().doubleValue()<0){
                card.setMoney(new BigDecimal("0"));
            }
            cardMapper.updateByPrimaryKeySelective(card);
        }
    }

}
